/**
 * 用户管理
 */
Ext.namespace('cmc.Company');
cmc.Company.fields=[];
cmc.Company.className="com.wef.cdm.entity.Company";	
var length=0;

length=cmc.Company.fields.length;
cmc.Company.fields[length]={};
cmc.Company.fields[length].fieldLabel="公司代码";
cmc.Company.fields[length].colWidth=150;
cmc.Company.fields[length].fieldName="companyCode";
cmc.Company.fields[length].dataType="String";
cmc.Company.fields[length].displayInList=true; 
cmc.Company.fields[length].displayInQuery=true; 

length=cmc.Company.fields.length;
cmc.Company.fields[length]={};
cmc.Company.fields[length].fieldLabel="公司名称";
cmc.Company.fields[length].colWidth=450;
cmc.Company.fields[length].fieldName="companyName";
cmc.Company.fields[length].dataType="String";
cmc.Company.fields[length].displayInList=true; 
cmc.Company.fields[length].displayInQuery=true; 

UserManager = function(){
	UserManager.superclass.constructor.call(this);
};

Ext.extend(UserManager, Gfa.view.PopupEditSimpleView, {
	init : function(){
		this.service = UserService;
		this.className = 'com.wef.system.entity.User';
		this.methodName = 'saveOrUpdateUserWithRole';
		this.pageSize = 15;
		this.popupWidth = 760;
		this.popupHeight = 245;
		this.popupTitle = '用户管理';
		this.operation = new Gfa.core.Operation();
		this.reader = new Gfa.data.DwrReader({}, [
        	{name : 'userCode'},
			{name : 'officeCode'},
			{name : 'position'},
			{name : 'telephone1'},
			{name : 'email'},
			{name : 'userName'},
			{name : 'firstName'},
			{name : 'lastName'},
			{name : 'middleName'},
			{name : 'password'},
			{name : 'fax'},
			{name : 'userType'},
			{name : 'companyCode'}
		]);
		
		this.cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			{header:'用户名',width:100,sortable:true,dataIndex:'userCode'},
			{header:'名字',width:100,sortable:true,dataIndex:'userName'},
			{header:'办事处',width:100,sortable:true,dataIndex:'officeCode'},
			{header:'职位',width:100,sortable:true,dataIndex:'position'},
			{header:'电话',width:100,sortable:true,dataIndex:'telephone1'},
			{header:'传真',width:100,sortable:true,dataIndex:'fax'},
			{header:'邮件地址', width:100,sortable:true,dataIndex:'email'},
			{header:'用户类型', width:100,sortable:true,dataIndex:'userType'}
		]);
		

		this.showExportToExcel = true ;
		this.showExportAllToExcel = true ;//是否显示导出全部按钮
	},
	
	createQueryComposite : function(){
		var dsCombo = new Gfa.data.Store({
			reader : new Gfa.data.DwrReader({}, [
	          	{name : 'roleId'},
				{name : 'roleName'},
	             {name : 'roleDesc'}
			])
		});
		
		var cm = new Ext.grid.ColumnModel([
			{header : '角色代码', dataIndex: 'roleName'},
			{header : '角色名称', dataIndex: 'roleDesc'}
		]);

		var fileldset = new Ext.form.FieldSet({
			title : i18n.global.search,
			border : true,
			collapsible : false,
			autoHeight : true,
			labelWidth : 60,
			layout : 'column',
			items : [{
					columnWidth: .3,
					layout : 'form',
					border : false,
					items : [{
						xtype : 'textfield',
						fieldLabel : '用户名',
						name : 'userCode',
						maxLength : 50,
						queryField : {
							condition : Gfa.GlobalConstant.CONDITION_EQ
						},
						anchor : '-25'
					}]
				},{
					columnWidth: .3,
					layout : 'form',
					border : false,
					items : [{
						xtype : 'gfaCombobox',
						fieldLabel : '角色',
						name : 'roleId',
//						matchType : 'likeanywhere',
						displayField : 'roleName',
						valueField : 'roleId',
						store : dsCombo,
						cm : cm,
						listType : 'grid',
						listWidth : 210,
						typeAhead : true,
						maxHeight: 400,
				        pageSize : 15,
				        autoMatchWhenExpand : true,
				        forceSelection : true,
						readOnly : false,
						queryObjectName : 'com.wef.system.entity.Role',
						fromAssociateCollection:'roleUsers',
						queryField : {
							condition : Gfa.GlobalConstant.CONDITION_EQ
						},
						orderByProps : {'roleName' : 'desc'},
						triggerAction : 'all',
						selectOnFocus : true,
						listeners : {select:function(){}},
						anchor : '-25',
						enableHdMenu : false
					}]
				}]
		});
		return fileldset;
	},
	
	createEditComposite : function(){
	
		var officeDs = new Ext.data.Store({
	        proxy : new Gfa.data.DwrProxy(CommonService),    
	        reader : new Gfa.data.DwrReader({}, ['officeCode', 'officeName']),
	        pruneModifiedRecords : true,
	        remoteSort : false
	    });
	    
	    officeDs.load({params : {dwrMethod : "loadAll", 
				dwrArguments : ['com.wef.system.entity.Office']}});
	    
	    this.dsRoleFrom = new Ext.data.Store({
	        proxy : new Gfa.data.DwrProxy(CommonService),    
	        reader : new Gfa.data.DwrReader({}, ['roleId', 'roleName']),
	        pruneModifiedRecords : true,
	        remoteSort : false
	    });
	    
	    this.dsRoleTo = new Ext.data.Store({
	        proxy : new Gfa.data.DwrProxy(UserService),    
	        reader : new Gfa.data.DwrReader({}, ['roleId', 'roleName']),
	        pruneModifiedRecords : true,
	        remoteSort : false
	    });
		
	    this.role = new Ext.ux.ItemSelector({
			name : "role",
			fieldLabel : system.Role.Role,
			dataFields : [],
			fromData : [],
			toData : [],
			msWidth : 90,
			msHeight : 125,
			valueField : "roleId",
			displayField : "roleName",
			imagePath : "widgets/ext-2.2.1/resources/images/multiselect/",
			switchToFrom : true,
			toLegend : "已选",
			fromLegend : "可选",
			toSortField : 'roleName',
			fromStore : this.dsRoleFrom,
			toStore : this.dsRoleTo
		});

		return new Ext.FormPanel({
			labelAlign : 'left',
		    labelWidth : 70,
		    border : false,
		    frame : true,
		    layout : 'column', 
		    items: [{
	            columnWidth: 0.3,
	            layout: 'form',
	            labelWidth:70,
	            defaults: {anchor:'-25'},
	            defaultType: 'textfield',
	            items: [{
	                fieldLabel: system.User.userCode,
	                name: 'userCode',
	                vtype : 'alphanum',
	                maxLength : 30,
	                allowBlank: false
	            }, {
	                fieldLabel: system.User.firstName,
	                maxLength : 20,
	                name: 'firstName'
	            }, {
	            	fieldLabel: system.User.lastName,
	            	maxLength : 20,
	                name: 'lastName'
	            }, {
	                fieldLabel: system.User.telephone1,
	                name: 'telephone1',
	                vtype: 'phone'
	            }, {
	                fieldLabel: '传真',
	                name: 'fax',
	                vtype: 'phone'
	            }, {
	                fieldLabel: system.User.userType,
	                maxLength : 20,
	                name: 'userType'
	            }]
	        }, {
	            columnWidth:0.3,
	            layout: 'form',
	            labelWidth:80,
	            defaults: {anchor:'-25'},
	            defaultType: 'textfield',
	            items: [{
	                fieldLabel: system.User.password,
	                name: 'password',
	                inputType: 'password'
	            },{
	            	fieldLabel: system.User.middleName,
	            	maxLength : 10,
	                name: 'middleName'
	           }, {
	            	fieldLabel: system.User.email,
	                name: 'email',
	                vtype : 'email'
	            },{
	            	fieldLabel: system.User.position,
	            	maxLength : 40,
	                name: 'position'
	            }, {            	
	            	xtype : 'combo',
	                fieldLabel : system.User.officeCode,
	                store : officeDs,
	                listWidth : 200,
	                name : 'officeCode',
	                allowBlank : false,
	                displayField : 'officeCode',
	                displayField : 'officeName',
	                typeAhead : true,
	                minChars : 0,
	                pageSize : 15,
	                mode : 'local',
	                triggerAction : 'all',
	                emptyText : '请选择...',
	                selectOnFocus : true,
	                editable : false 
	            },{
	            	xtype:'gfaquicksearchfield',
	            	fieldLabel: '所属公司',
	                name: 'companyCode',
	                entityConfig : cmc.Company,
	                valueField : 'companyCode',
	                displayField : 'companyName',
	                title : '选择公司'
	            }]  
	    	}, {
		            columnWidth:0.4,
		            layout: 'form',
		            labelWidth:40,
		            defaults: {anchor:'-25'},
		            items: [this.role]    
	        }]
		});
	},
	
	/**
	 * 弹出窗口的保存动作。
	 */
	saveAction : function(){
		if(!this.frmPopup.form.isValid())
			return;
		var record;
		if(this.operation.eidtMode == 'new'){
			record = this.store.insertNewRecord();
			this.frmPopup.form.updateRecord(record);
		}else if(this.operation.eidtMode=='edit'){
			record = this.operation.getSelected();
			if (record.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED)
				record.set('rowStatus',Gfa.GlobalConstant.ROWSTATUS_MODIFIED);
			this.frmPopup.form.updateRecord(record);
		}else{
			record = this.operation.getSelected();
			this.frmPopup.form.updateRecord(record);
		}
		
		var roleIds = this.role.getValue().split(",");
		var roleUsers = [];
		var role = [];
		if(roleIds!=""){
			for(var i=0; i<roleIds.length; i++){
				if(roleIds[i].length > 0)
					roleUsers.push({role: {roleId : roleIds[i]}});
					role.push(this.dsRoleTo.data.items[i].data);
			}
		}
		if(roleUsers.length > 0){
			record.set('roleUsers', roleUsers);
			record.set('role', role);
			
		}
		this.winPopup.hide();
	},
	
	onPopupShow : function(){
		//如果当前为新增模式，则调用子类的onPopupShow方法。
		if(this.operation.eidtMode == 'new'){
			this.dsRoleTo.removeAll();
			this.dsRoleFrom.removeAll();
			this.dsRoleFrom.load({params : {dwrMethod : "loadAll", 
				dwrArguments : ['com.wef.system.entity.Role']}});
		}else{
			this.dsRoleTo.removeAll();
			this.dsRoleFrom.removeAll();
			var rec = this.operation.getSelected();

			var roles = [];
			if (rec.data.role == undefined) { //首次加载
				//this.dsRoleTo.load({params : {dwrMethod : "findUserRoleList", dwrArguments : [rec.data.userId]}});
				UserService.findUserRoleList(rec.data.userId,{
					callback : function(result) {
						//this.dsRoleTo.load({params : {dwrMethod : "findUserRoleList", dwrArguments : [rec.data.userId]}});
						for (var roleCount = 0; roleCount < result.length; roleCount++) {
							roles.push(result[roleCount]);
						}	
						rec.set('role',roles);				
					},
					async : false
				});	
			}else{
				roles = rec.data.role;
			}
			
			var queryInfo={};
			    	queryInfo.queryObjectName = 'com.wef.system.entity.Role';
			    	queryInfo.listType = 'list';
			    	queryInfo.conjunctionType = "and";
			    	var fields = [];     	
					for (var roleCount = 0; roleCount < roles.length; roleCount++) {
						var field = {};
				    	field.condition = "neq";
				    	field.fieldName = "roleId";
				    	field.fieldValueString = roles[roleCount].IDValue;
				    	field.fieldParam = 'id' + roleCount;
				    	fields.push(field);
					}		
					queryInfo.fields = fields;
					
					this.dsRoleTo.proxy = new Ext.data.MemoryProxy(roles);
					this.dsRoleTo.load();
					
					this.dsRoleFrom.load({params : {dwrMethod : "findByQueryInit", dwrArguments : [queryInfo, []], start : 0}});
		
				
		}
		
	},
	
	unhideAction : function() {
		this.pnlQuery.form.reset();
		this.store.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	}
});

Ext.onReady(function(){
	new UserManager();
});